/**
 * 游戏上传表单验证和API集成
 * 针对游戏标题、分类、描述、游戏文件和缩略图进行验证并与后端API通信
 */

document.addEventListener('DOMContentLoaded', function() {
    // 获取上传表单元素
    const uploadForm = document.getElementById('uploadGameForm');
    const uploadModal = document.getElementById('uploadModal');
    
    // 如果表单不存在，则不执行后续代码
    if (!uploadForm) return;

    // 确保模态窗口内容可滚动
    if (uploadModal) {
        const modalContent = uploadModal.querySelector('.modal-content');
        if (modalContent) {
            modalContent.style.maxHeight = '90vh';
            modalContent.style.overflowY = 'auto';
        }
    }

    // 添加取消按钮
    const submitButton = uploadForm.querySelector('button[type="submit"]');
    if (submitButton) {
        const formActions = submitButton.parentElement;
        
        // 创建取消按钮
        const cancelButton = document.createElement('button');
        cancelButton.type = 'button';
        cancelButton.className = 'btn-cancel';
        cancelButton.textContent = '取消';
        cancelButton.style.marginLeft = '10px';
        cancelButton.style.backgroundColor = '#e0e0e0';
        cancelButton.style.color = '#333';
        cancelButton.style.border = 'none';
        cancelButton.style.padding = '10px 20px';
        cancelButton.style.borderRadius = '4px';
        cancelButton.style.cursor = 'pointer';
        
        // 添加取消按钮点击事件
        cancelButton.addEventListener('click', function() {
            // 关闭模态框
            if (uploadModal) {
                uploadModal.style.display = 'none';
            }
            // 重置表单
            uploadForm.reset();
            // 清除所有错误消息
            const errorMessages = uploadForm.querySelectorAll('.error-message');
            errorMessages.forEach(error => error.remove());
            // 重置表单字段边框颜色
            const formFields = uploadForm.querySelectorAll('input, select, textarea');
            formFields.forEach(field => field.style.borderColor = '');
        });
        
        // 将取消按钮添加到表单操作区域
        formActions.appendChild(cancelButton);
    }

    // 获取所有表单字段
    const gameTitle = document.getElementById('gameTitle');
    const gameCategory = document.getElementById('gameCategory');
    const gameDescription = document.getElementById('gameDescription');
    const gameFile = document.getElementById('gameFile');
    const gameThumbnail = document.getElementById('gameThumbnail');
    
    // 错误消息显示函数
    function showError(element, message) {
        // 移除可能已存在的错误消息
        const existingError = element.parentElement.querySelector('.error-message');
        if (existingError) {
            existingError.remove();
        }
        
        // 创建错误消息元素
        const errorElement = document.createElement('div');
        errorElement.className = 'error-message';
        errorElement.style.color = '#e74c3c';
        errorElement.style.fontSize = '12px';
        errorElement.style.marginTop = '5px';
        errorElement.textContent = message;
        
        // 将错误消息添加到表单字段后
        element.parentElement.appendChild(errorElement);
        
        // 给字段添加错误样式
        element.style.borderColor = '#e74c3c';
    }
    
    // 清除错误消息
    function clearError(element) {
        const errorElement = element.parentElement.querySelector('.error-message');
        if (errorElement) {
            errorElement.remove();
        }
        element.style.borderColor = '';
    }
    
    // 显示表单错误信息
    function showFormError(message) {
        const errorMsgElement = document.getElementById('uploadErrorMsg');
        if (errorMsgElement) {
            errorMsgElement.textContent = message;
            errorMsgElement.style.display = 'block';
            
            // 自动消失
            setTimeout(() => {
                errorMsgElement.style.display = 'none';
            }, 5000);
        }
    }
    
    // 显示表单成功信息
    function showFormSuccess(message) {
        // 检查是否存在成功消息元素
        let successMsgElement = document.getElementById('uploadSuccessMsg');
        
        // 如果不存在，创建一个
        if (!successMsgElement) {
            successMsgElement = document.createElement('div');
            successMsgElement.id = 'uploadSuccessMsg';
            successMsgElement.style.backgroundColor = '#4caf50';
            successMsgElement.style.color = 'white';
            successMsgElement.style.padding = '10px 15px';
            successMsgElement.style.borderRadius = '5px';
            successMsgElement.style.marginBottom = '15px';
            successMsgElement.style.display = 'none';
            
            // 添加到表单前面
            if (uploadForm.parentNode) {
                uploadForm.parentNode.insertBefore(successMsgElement, uploadForm);
            } else {
                document.querySelector('main').appendChild(successMsgElement);
            }
        }
        
        // 设置消息并显示
        successMsgElement.textContent = message;
        successMsgElement.style.display = 'block';
        
        // 5秒后自动消失
        setTimeout(() => {
            successMsgElement.style.display = 'none';
        }, 5000);
    }
    
    // 验证游戏标题
    function validateGameTitle() {
        const value = gameTitle.value.trim();
        
        if (value === '') {
            showError(gameTitle, '请输入游戏标题');
            return false;
        } else if (value.length < 2) {
            showError(gameTitle, '游戏标题至少需要2个字符');
            return false;
        } else if (value.length > 50) {
            showError(gameTitle, '游戏标题不能超过50个字符');
            return false;
        } else {
            clearError(gameTitle);
            return true;
        }
    }
    
    // 验证游戏分类
    function validateGameCategory() {
        if (gameCategory.value === '') {
            showError(gameCategory, '请选择游戏分类');
            return false;
        } else {
            clearError(gameCategory);
            return true;
        }
    }
    
    // 验证游戏描述
    function validateGameDescription() {
        const value = gameDescription.value.trim();
        
        if (value === '') {
            showError(gameDescription, '请输入游戏描述');
            return false;
        } else if (value.length < 10) {
            showError(gameDescription, '游戏描述至少需要10个字符');
            return false;
        } else if (value.length > 500) {
            showError(gameDescription, '游戏描述不能超过500个字符');
            return false;
        } else {
            clearError(gameDescription);
            return true;
        }
    }
    
    // 验证游戏文件
    function validateGameFile() {
        if (gameFile.files.length === 0) {
            showError(gameFile, '请选择游戏文件');
            return false;
        }
        
        const file = gameFile.files[0];
        const fileSize = file.size / 1024 / 1024; // 转换为MB
        const fileName = file.name.toLowerCase();
        const validExtensions = ['.zip', '.rar', '.html', '.exe', '.swf'];
        
        let isValidExtension = false;
        for (const ext of validExtensions) {
            if (fileName.endsWith(ext)) {
                isValidExtension = true;
                break;
            }
        }
        
        if (!isValidExtension) {
            showError(gameFile, '游戏文件格式不支持，请使用zip、rar、html、exe或swf格式');
            return false;
        } else if (fileSize > 100) {
            showError(gameFile, '游戏文件大小不能超过100MB');
            return false;
        } else {
            clearError(gameFile);
            return true;
        }
    }
    
    // 验证游戏缩略图
    function validateGameThumbnail() {
        if (gameThumbnail.files.length === 0) {
            showError(gameThumbnail, '请选择游戏缩略图');
            return false;
        }
        
        const file = gameThumbnail.files[0];
        const fileSize = file.size / 1024 / 1024; // 转换为MB
        const fileName = file.name.toLowerCase();
        const validExtensions = ['.jpg', '.jpeg', '.png', '.gif', '.webp'];
        
        let isValidExtension = false;
        for (const ext of validExtensions) {
            if (fileName.endsWith(ext)) {
                isValidExtension = true;
                break;
            }
        }
        
        if (!isValidExtension) {
            showError(gameThumbnail, '图片格式不支持，请使用jpg、jpeg、png、gif或webp格式');
            return false;
        } else if (fileSize > 5) {
            showError(gameThumbnail, '图片大小不能超过5MB');
            return false;
        } else {
            clearError(gameThumbnail);
            return true;
        }
    }
    
    // 添加实时验证事件
    gameTitle.addEventListener('blur', validateGameTitle);
    gameCategory.addEventListener('change', validateGameCategory);
    gameDescription.addEventListener('blur', validateGameDescription);
    gameFile.addEventListener('change', validateGameFile);
    gameThumbnail.addEventListener('change', validateGameThumbnail);
    
    // 表单提交事件处理
    uploadForm.addEventListener('submit', async function(event) {
        // 阻止默认提交行为
        event.preventDefault();
        
        // 验证所有字段
        const isTitleValid = validateGameTitle();
        const isCategoryValid = validateGameCategory();
        const isDescriptionValid = validateGameDescription();
        const isFileValid = validateGameFile();
        const isThumbnailValid = validateGameThumbnail();
        
        // 如果所有验证都通过
        if (isTitleValid && isCategoryValid && isDescriptionValid && isFileValid && isThumbnailValid) {
            // 检查用户是否已登录（仅在非模拟模式下检查）
            if (!window.ApiClient || (!window.ApiClient.User.isLoggedIn() && !window.USE_MOCK_API)) {
                showFormError('请先登录再上传游戏');
                
                // 打开登录模态框
                const loginModal = document.getElementById('loginModal');
                if (loginModal) {
                    setTimeout(() => {
                        loginModal.style.display = 'block';
                    }, 1000);
                }
                return;
            }
            
            try {
                // 禁用提交按钮
                submitButton.disabled = true;
                
                // 创建并显示进度条容器
                const progressContainer = document.createElement('div');
                progressContainer.className = 'upload-progress-container';
                progressContainer.style.marginBottom = '20px';
                progressContainer.style.backgroundColor = '#f5f5f5';
                progressContainer.style.borderRadius = '4px';
                progressContainer.style.overflow = 'hidden';
                progressContainer.style.height = '24px';
                
                // 进度条
                const progressBar = document.createElement('div');
                progressBar.className = 'upload-progress-bar';
                progressBar.style.width = '0%';
                progressBar.style.height = '100%';
                progressBar.style.backgroundColor = '#27ae60';
                progressBar.style.transition = 'width 0.3s';
                progressBar.style.color = 'white';
                progressBar.style.textAlign = 'center';
                progressBar.style.fontSize = '12px';
                progressBar.style.lineHeight = '24px';
                progressBar.textContent = '0%';
                
                progressContainer.appendChild(progressBar);
                
                // 添加到表单顶部
                uploadForm.insertBefore(progressContainer, uploadForm.firstChild);
                
                // 准备游戏数据
                const gameData = {
                    title: gameTitle.value.trim(),
                    category: gameCategory.value,
                    description: gameDescription.value.trim()
                };
                
                // 进度回调函数
                const updateProgress = (percent) => {
                    progressBar.style.width = `${percent}%`;
                    progressBar.textContent = `${percent}%`;
                    
                    if (percent < 100) {
                        submitButton.textContent = `上传中 ${percent}%`;
                    } else {
                        submitButton.textContent = '处理中...';
                    }
                };
                
                // 使用API上传游戏
                console.log('开始上传游戏文件...', gameData);
                try {
                    console.log('检查登录状态:', window.ApiClient.User.isLoggedIn());
                    console.log('API模式:', window.ApiClient ? (window.USE_MOCK_API ? '模拟模式' : '真实模式') : '未初始化');
                    
                    const result = await window.ApiClient.Games.uploadGame(
                        gameData,
                        gameFile.files[0],
                        gameThumbnail.files[0],
                        updateProgress
                    );
                    
                    // 上传成功
                    console.log('游戏上传成功:', result);
                    
                    // 更新进度条为完成状态
                    progressBar.style.width = '100%';
                    progressBar.style.backgroundColor = '#27ae60';
                    progressBar.textContent = '上传完成!';
                    
                    if (result.success) {
                        uploadForm.reset();
                        // 清除预览图
                        const thumbnailPreview = document.getElementById('thumbnailPreview');
                        if (thumbnailPreview) {
                            thumbnailPreview.style.backgroundImage = 'none';
                            thumbnailPreview.style.display = 'none';
                        }
                        
                        // 显示成功消息
                        if (window.showNotification) {
                            window.showNotification(`游戏 "${result.game.title}" 上传成功！正在等待审核。`, 'success', 5000);
                        } else {
                            showFormSuccess('游戏上传成功！正在等待审核');
                        }
                        
                        // 将上传成功的游戏信息保存到本地存储（用于"我的游戏"页面）
                        if (result.game) {
                            try {
                                // 获取现有上传的游戏
                                let myGames = JSON.parse(localStorage.getItem('my_uploaded_games') || '[]');
                                // 添加新游戏到列表顶部
                                myGames.unshift(result.game);
                                // 限制保存的游戏数量
                                if (myGames.length > 20) myGames = myGames.slice(0, 20);
                                // 保存回本地存储
                                localStorage.setItem('my_uploaded_games', JSON.stringify(myGames));
                                
                                // 显示新上传的游戏
                                displayUploadedGame(result.game);
                                
                                // 滚动到"我的游戏"区域
                                const myGamesSection = document.querySelector('.my-games-section');
                                if (myGamesSection) {
                                    setTimeout(() => {
                                        myGamesSection.scrollIntoView({ behavior: 'smooth' });
                                    }, 500);
                                }
                            } catch (e) {
                                console.error('保存游戏到本地存储失败:', e);
                            }
                        }
                    }
                } catch (uploadError) {
                    console.error('游戏上传失败:', uploadError);
                    throw uploadError;
                }
                
            } catch (error) {
                console.error('游戏上传失败:', error);
                
                // 查找并移除进度条
                const progressContainer = uploadForm.querySelector('.upload-progress-container');
                if (progressContainer && progressContainer.parentNode) {
                    progressContainer.parentNode.removeChild(progressContainer);
                }
                
                // 显示错误消息
                let errorMessage = '游戏上传失败';
                if (error.message) {
                    errorMessage += ': ' + error.message;
                    // 特殊处理认证错误
                    if (error.message.includes('需要登录') || error.message.includes('login')) {
                        errorMessage = '请先登录再上传游戏。如果已登录，请尝试重新登录。';
                        // 可以添加自动展示登录模态框的代码
                        const loginModal = document.getElementById('loginModal');
                        if (loginModal) {
                            setTimeout(() => {
                                loginModal.style.display = 'block';
                            }, 1000);
                        }
                    }
                }
                
                showFormError(errorMessage);
                
                // 恢复按钮状态
                submitButton.disabled = false;
                submitButton.textContent = '上传游戏';
            }
        } else {
            console.log('表单验证失败');
            showFormError('请修正表单中的错误后再提交');
        }
    });
    
    // 为文件输入添加自定义样式和预览
    function setupFileInput(fileInput, previewContainerId, isImage) {
        const container = fileInput.parentElement;
        
        // 创建自定义按钮
        const customButton = document.createElement('div');
        customButton.className = 'custom-file-upload';
        customButton.textContent = `选择${isImage ? '图片' : '文件'}`;
        
        // 创建文件名显示区域
        const fileNameDisplay = document.createElement('span');
        fileNameDisplay.className = 'file-name';
        fileNameDisplay.textContent = '未选择文件';
        
        // 创建预览区域（如果提供了ID）
        let previewContainer = null;
        if (previewContainerId) {
            previewContainer = document.createElement('div');
            previewContainer.id = previewContainerId;
            previewContainer.className = 'file-preview';
            if (isImage) {
                previewContainer.style.marginTop = '10px';
                previewContainer.style.width = '100px';
                previewContainer.style.height = '100px';
                previewContainer.style.backgroundColor = '#f8f9fa';
                previewContainer.style.borderRadius = '4px';
                previewContainer.style.display = 'flex';
                previewContainer.style.alignItems = 'center';
                previewContainer.style.justifyContent = 'center';
            }
        }
        
        // 隐藏原始文件输入
        fileInput.style.opacity = '0';
        fileInput.style.position = 'absolute';
        fileInput.style.zIndex = '-1';
        
        // 将自定义元素添加到容器
        const wrapper = document.createElement('div');
        wrapper.className = 'file-input-wrapper';
        wrapper.style.display = 'flex';
        wrapper.style.alignItems = 'center';
        wrapper.style.gap = '10px';
        
        wrapper.appendChild(customButton);
        wrapper.appendChild(fileNameDisplay);
        
        container.appendChild(wrapper);
        if (previewContainer) {
            container.appendChild(previewContainer);
        }
        
        // 点击自定义按钮触发文件输入
        customButton.addEventListener('click', function() {
            fileInput.click();
        });
        
        // 文件选择后更新显示
        fileInput.addEventListener('change', function() {
            if (this.files.length > 0) {
                fileNameDisplay.textContent = this.files[0].name;
                
                // 如果是图片且有预览容器，显示预览
                if (isImage && previewContainer) {
                    const reader = new FileReader();
                    reader.onload = function(e) {
                        previewContainer.innerHTML = '';
                        const img = document.createElement('img');
                        img.src = e.target.result;
                        img.style.maxWidth = '100%';
                        img.style.maxHeight = '100%';
                        previewContainer.appendChild(img);
                    };
                    reader.readAsDataURL(this.files[0]);
                }
            } else {
                fileNameDisplay.textContent = '未选择文件';
                if (previewContainer) {
                    previewContainer.innerHTML = '';
                }
            }
        });
    }
    
    // 设置文件输入样式和预览
    setupFileInput(gameFile, null, false);
    setupFileInput(gameThumbnail, 'thumbnailPreview', true);
    
    // 显示用户上传的游戏
    function displayUploadedGame(game) {
        // 检查是否需要创建"我的游戏"区域
        let myGamesSection = document.querySelector('.my-games-section');
        
        if (!myGamesSection) {
            // 创建"我的游戏"区域
            myGamesSection = document.createElement('section');
            myGamesSection.className = 'my-games-section';
            myGamesSection.style.backgroundColor = '#ffffff';
            myGamesSection.style.borderRadius = '8px';
            myGamesSection.style.padding = '25px';
            myGamesSection.style.marginBottom = '30px';
            myGamesSection.style.boxShadow = '0 2px 10px rgba(0, 0, 0, 0.05)';
            
            // 创建标题
            const title = document.createElement('h2');
            title.textContent = '我的游戏';
            myGamesSection.appendChild(title);
            
            // 创建游戏卡片容器
            const gamesGrid = document.createElement('div');
            gamesGrid.className = 'games-grid';
            gamesGrid.style.display = 'grid';
            gamesGrid.style.gridTemplateColumns = 'repeat(auto-fit, minmax(220px, 1fr))';
            gamesGrid.style.gap = '20px';
            gamesGrid.style.marginTop = '20px';
            myGamesSection.appendChild(gamesGrid);
            
            // 将"我的游戏"区域添加到主体内容区域
            const mainContent = document.querySelector('main');
            if (mainContent) {
                mainContent.insertBefore(myGamesSection, mainContent.firstChild);
            } else {
                console.error('无法找到主体内容区域');
                return;
            }
        }
        
        // 检查游戏卡片容器
        let gamesGrid = myGamesSection.querySelector('.games-grid');
        if (!gamesGrid) {
            console.error('无法找到游戏卡片容器');
            return;
        }
        
        // 创建新游戏卡片
        const gameCard = document.createElement('div');
        gameCard.className = 'game-card';
        gameCard.style.backgroundColor = '#ffffff';
        gameCard.style.borderRadius = '8px';
        gameCard.style.overflow = 'hidden';
        gameCard.style.boxShadow = '0 2px 10px rgba(0, 0, 0, 0.05)';
        gameCard.style.transition = 'transform 0.3s, box-shadow 0.3s';
        gameCard.style.border = '1px solid #f0f0f0';
        gameCard.setAttribute('data-game-id', game.id);
        
        // 设置游戏卡片内容
        gameCard.innerHTML = `
            <div class="game-card-status" style="position: absolute; top: 10px; right: 10px; background-color: #ff9800; color: white; padding: 2px 8px; border-radius: 10px; font-size: 12px;">
                ${game.status === 'approved' ? '已批准' : '审核中'}
            </div>
            <img src="${game.thumbnail || 'https://via.placeholder.com/300x200?text=游戏缩略图'}" alt="${game.title}" style="width: 100%; height: 150px; object-fit: cover;">
            <div style="padding: 15px;">
                <h3 style="margin: 0 0 10px 0; font-size: 18px;">${game.title}</h3>
                <p style="margin: 0 0 10px 0; color: #666; font-size: 14px; display: -webkit-box; -webkit-line-clamp: 2; -webkit-box-orient: vertical; overflow: hidden;">${game.description}</p>
                <div style="display: flex; justify-content: space-between; align-items: center;">
                    <span style="background-color: #e0f2f1; color: #00796b; padding: 3px 8px; border-radius: 4px; font-size: 12px;">${game.category}</span>
                    <span style="color: #888; font-size: 12px;">${new Date(game.createdAt).toLocaleDateString()}</span>
                </div>
                <div style="margin-top: 10px; text-align: center; padding: 5px; background-color: #f5f5f5; border-radius: 4px; color: #555; font-size: 12px;">
                    点击卡片立即预览游戏
                </div>
            </div>
        `;
        
        // 添加点击事件
        gameCard.addEventListener('click', function() {
            // 获取游戏ID
            const gameId = this.getAttribute('data-game-id');
            
            // 从localStorage中获取游戏信息
            try {
                const myGames = JSON.parse(localStorage.getItem('my_uploaded_games') || '[]');
                const gameInfo = myGames.find(g => g.id == gameId);
                
                if (gameInfo) {
                    // 创建游戏预览/游玩模态框
                    const gamePreviewModal = document.createElement('div');
                    gamePreviewModal.className = 'modal game-preview-modal';
                    gamePreviewModal.style.display = 'block';
                    gamePreviewModal.style.position = 'fixed';
                    gamePreviewModal.style.zIndex = '1000';
                    gamePreviewModal.style.left = '0';
                    gamePreviewModal.style.top = '0';
                    gamePreviewModal.style.width = '100%';
                    gamePreviewModal.style.height = '100%';
                    gamePreviewModal.style.overflow = 'auto';
                    gamePreviewModal.style.backgroundColor = 'rgba(0,0,0,0.6)';
                    
                    // 创建模态内容
                    const modalContent = document.createElement('div');
                    modalContent.className = 'modal-content game-preview-content';
                    modalContent.style.backgroundColor = '#fefefe';
                    modalContent.style.margin = '5% auto';
                    modalContent.style.padding = '20px';
                    modalContent.style.width = '80%';
                    modalContent.style.maxWidth = '900px';
                    modalContent.style.borderRadius = '8px';
                    modalContent.style.boxShadow = '0 4px 8px rgba(0, 0, 0, 0.2)';
                    modalContent.style.position = 'relative';
                    
                    // 添加关闭按钮
                    const closeBtn = document.createElement('span');
                    closeBtn.className = 'close-button';
                    closeBtn.innerHTML = '&times;';
                    closeBtn.style.position = 'absolute';
                    closeBtn.style.right = '20px';
                    closeBtn.style.top = '15px';
                    closeBtn.style.fontSize = '28px';
                    closeBtn.style.fontWeight = 'bold';
                    closeBtn.style.cursor = 'pointer';
                    closeBtn.style.color = '#aaa';
                    closeBtn.onclick = function() {
                        document.body.removeChild(gamePreviewModal);
                    };
                    
                    // 游戏头部信息
                    const gameHeader = document.createElement('div');
                    gameHeader.className = 'game-preview-header';
                    gameHeader.style.display = 'flex';
                    gameHeader.style.alignItems = 'flex-start';
                    gameHeader.style.marginBottom = '20px';
                    gameHeader.style.paddingBottom = '15px';
                    gameHeader.style.borderBottom = '1px solid #eee';
                    
                    // 游戏缩略图
                    const gameThumbnail = document.createElement('img');
                    gameThumbnail.src = gameInfo.thumbnail || 'https://via.placeholder.com/150x150?text=预览图';
                    gameThumbnail.alt = gameInfo.title;
                    gameThumbnail.style.width = '120px';
                    gameThumbnail.style.height = '120px';
                    gameThumbnail.style.objectFit = 'cover';
                    gameThumbnail.style.borderRadius = '8px';
                    gameThumbnail.style.marginRight = '20px';
                    
                    // 游戏信息
                    const gameInfoDiv = document.createElement('div');
                    gameInfoDiv.style.flex = '1';
                    
                    const gameTitle = document.createElement('h2');
                    gameTitle.textContent = gameInfo.title;
                    gameTitle.style.margin = '0 0 10px 0';
                    gameTitle.style.color = '#333';
                    
                    const gameStatus = document.createElement('div');
                    gameStatus.style.display = 'inline-block';
                    gameStatus.style.backgroundColor = gameInfo.status === 'approved' ? '#4caf50' : '#ff9800';
                    gameStatus.style.color = 'white';
                    gameStatus.style.padding = '4px 10px';
                    gameStatus.style.borderRadius = '15px';
                    gameStatus.style.fontSize = '12px';
                    gameStatus.style.marginBottom = '10px';
                    gameStatus.textContent = gameInfo.status === 'approved' ? '已批准' : '审核中（预览模式）';
                    
                    const gameCategory = document.createElement('div');
                    gameCategory.style.fontSize = '14px';
                    gameCategory.style.color = '#666';
                    gameCategory.style.marginBottom = '5px';
                    gameCategory.innerHTML = `<strong>分类:</strong> <span style="background-color: #e0f2f1; color: #00796b; padding: 2px 8px; border-radius: 4px;">${gameInfo.category}</span>`;
                    
                    const gameDate = document.createElement('div');
                    gameDate.style.fontSize = '14px';
                    gameDate.style.color = '#666';
                    gameDate.innerHTML = `<strong>上传时间:</strong> ${new Date(gameInfo.createdAt).toLocaleString()}`;
                    
                    // 拼接游戏信息
                    gameInfoDiv.appendChild(gameTitle);
                    gameInfoDiv.appendChild(gameStatus);
                    gameInfoDiv.appendChild(gameCategory);
                    gameInfoDiv.appendChild(gameDate);
                    
                    // 拼接游戏头部
                    gameHeader.appendChild(gameThumbnail);
                    gameHeader.appendChild(gameInfoDiv);
                    
                    // 创建游戏描述
                    const gameDescription = document.createElement('div');
                    gameDescription.style.marginBottom = '20px';
                    gameDescription.style.padding = '15px';
                    gameDescription.style.backgroundColor = '#f9f9f9';
                    gameDescription.style.borderRadius = '8px';
                    
                    const descTitle = document.createElement('h3');
                    descTitle.textContent = '游戏描述';
                    descTitle.style.margin = '0 0 10px 0';
                    descTitle.style.fontSize = '16px';
                    descTitle.style.color = '#333';
                    
                    const descContent = document.createElement('p');
                    descContent.textContent = gameInfo.description;
                    descContent.style.margin = '0';
                    descContent.style.fontSize = '14px';
                    descContent.style.color = '#666';
                    descContent.style.lineHeight = '1.6';
                    
                    gameDescription.appendChild(descTitle);
                    gameDescription.appendChild(descContent);
                    
                    // 创建游戏框架容器
                    const gameFrameContainer = document.createElement('div');
                    gameFrameContainer.style.marginTop = '20px';
                    
                    const frameTitle = document.createElement('h3');
                    frameTitle.textContent = '游戏预览';
                    frameTitle.style.margin = '0 0 15px 0';
                    frameTitle.style.fontSize = '18px';
                    frameTitle.style.color = '#333';
                    
                    // 创建模拟游戏界面（由于是模拟环境，我们创建一个简单的贪吃蛇游戏界面）
                    const gameCanvas = document.createElement('div');
                    gameCanvas.style.width = '100%';
                    gameCanvas.style.height = '400px';
                    gameCanvas.style.backgroundColor = '#333';
                    gameCanvas.style.borderRadius = '8px';
                    gameCanvas.style.position = 'relative';
                    gameCanvas.style.overflow = 'hidden';
                    
                    // 模拟贪吃蛇游戏
                    if (gameInfo.title.includes('贪吃蛇')) {
                        // 创建游戏提示
                        const gameInstructions = document.createElement('div');
                        gameInstructions.style.position = 'absolute';
                        gameInstructions.style.top = '50%';
                        gameInstructions.style.left = '50%';
                        gameInstructions.style.transform = 'translate(-50%, -50%)';
                        gameInstructions.style.color = 'white';
                        gameInstructions.style.textAlign = 'center';
                        gameInstructions.style.width = '80%';
                        gameInstructions.innerHTML = `
                            <h3>贪吃蛇游戏 - 游戏控制说明</h3>
                            <div style="background-color: rgba(0,0,0,0.5); padding: 15px; border-radius: 8px; margin-top: 10px;">
                                <p style="margin: 0 0 10px 0;"><strong>游戏控制：</strong></p>
                                <p style="margin: 0 0 5px 0;">⬆️ 上箭头：向上移动</p>
                                <p style="margin: 0 0 5px 0;">⬇️ 下箭头：向下移动</p>
                                <p style="margin: 0 0 5px 0;">⬅️ 左箭头：向左移动</p>
                                <p style="margin: 0 0 5px 0;">➡️ 右箭头：向右移动</p>
                                <p style="margin: 0 0 5px 0;">空格键：暂停/继续 或 重新开始</p>
                                <p style="margin: 15px 0 0 0; color: #ffeb3b;">点击下方"开始游戏"按钮即可开始游戏！</p>
                            </div>
                        `;
                        
                        gameCanvas.appendChild(gameInstructions);
                        
                        // 添加开始游戏按钮
                        const startButton = document.createElement('button');
                        startButton.textContent = '开始游戏';
                        startButton.style.display = 'block';
                        startButton.style.margin = '15px auto';
                        startButton.style.padding = '10px 25px';
                        startButton.style.backgroundColor = '#4caf50';
                        startButton.style.color = 'white';
                        startButton.style.border = 'none';
                        startButton.style.borderRadius = '4px';
                        startButton.style.cursor = 'pointer';
                        startButton.style.fontSize = '16px';
                        
                        startButton.onclick = function() {
                            // 清空画布
                            gameCanvas.innerHTML = '';
                            
                            // 创建游戏画布
                            const canvas = document.createElement('canvas');
                            canvas.width = gameCanvas.offsetWidth;
                            canvas.height = gameCanvas.offsetHeight;
                            canvas.style.display = 'block';
                            gameCanvas.appendChild(canvas);
                            
                            // 初始化贪吃蛇游戏
                            initSnakeGame(canvas);
                        };
                        
                        gameFrameContainer.appendChild(frameTitle);
                        gameFrameContainer.appendChild(gameCanvas);
                        gameFrameContainer.appendChild(startButton);
                    } else {
                        // 其他游戏类型的占位符
                        const placeholderText = document.createElement('div');
                        placeholderText.style.position = 'absolute';
                        placeholderText.style.top = '50%';
                        placeholderText.style.left = '50%';
                        placeholderText.style.transform = 'translate(-50%, -50%)';
                        placeholderText.style.color = 'white';
                        placeholderText.style.textAlign = 'center';
                        placeholderText.innerHTML = `<h3>${gameInfo.title}</h3><p>游戏加载中，模拟环境尚未实现此游戏的实际加载。</p>`;
                        
                        gameCanvas.appendChild(placeholderText);
                        
                        gameFrameContainer.appendChild(frameTitle);
                        gameFrameContainer.appendChild(gameCanvas);
                    }
                    
                    // 拼接模态内容
                    modalContent.appendChild(closeBtn);
                    modalContent.appendChild(gameHeader);
                    modalContent.appendChild(gameDescription);
                    modalContent.appendChild(gameFrameContainer);
                    
                    // 将模态内容添加到模态框
                    gamePreviewModal.appendChild(modalContent);
                    
                    // 将模态框添加到页面
                    document.body.appendChild(gamePreviewModal);
                    
                    // 添加点击关闭模态框
                    gamePreviewModal.addEventListener('click', function(event) {
                        if (event.target === gamePreviewModal) {
                            document.body.removeChild(gamePreviewModal);
                        }
                    });
                } else {
                    // 游戏信息不存在
                    if (window.showNotification) {
                        window.showNotification('无法找到游戏信息', 'error');
                    }
                }
            } catch (e) {
                console.error('加载游戏信息失败:', e);
                if (window.showNotification) {
                    window.showNotification('加载游戏信息失败', 'error');
                }
            }
        });
        
        // 添加悬停效果
        gameCard.addEventListener('mouseenter', function() {
            this.style.transform = 'translateY(-5px)';
            this.style.boxShadow = '0 8px 15px rgba(0, 0, 0, 0.1)';
        });
        
        gameCard.addEventListener('mouseleave', function() {
            this.style.transform = 'translateY(0)';
            this.style.boxShadow = '0 2px 10px rgba(0, 0, 0, 0.05)';
        });
        
        // 将新游戏卡片添加到最前面
        if (gamesGrid.firstChild) {
            gamesGrid.insertBefore(gameCard, gamesGrid.firstChild);
        } else {
            gamesGrid.appendChild(gameCard);
        }
    }
    
    // 页面加载时显示之前上传的所有游戏
    function displayAllUploadedGames() {
        try {
            const myGames = JSON.parse(localStorage.getItem('my_uploaded_games') || '[]');
            if (myGames.length > 0) {
                // 遍历并显示每个游戏
                myGames.forEach(game => {
                    displayUploadedGame(game);
                });
            }
        } catch (e) {
            console.error('加载已上传游戏失败:', e);
        }
    }
    
    // 页面加载时显示之前上传的游戏
    displayAllUploadedGames();
}); 

// 贪吃蛇游戏逻辑
function initSnakeGame(canvas) {
    const ctx = canvas.getContext('2d');
    const gridSize = 20;
    const canvasWidth = canvas.width - (canvas.width % gridSize);
    const canvasHeight = canvas.height - (canvas.height % gridSize);
    
    let snake = [
        {x: 5 * gridSize, y: 5 * gridSize},
        {x: 4 * gridSize, y: 5 * gridSize},
        {x: 3 * gridSize, y: 5 * gridSize}
    ];
    
    let direction = 'right';
    let food = generateFood();
    let score = 0;
    let gameSpeed = 120;
    let gameLoop;
    let isPaused = false;
    
    // 生成食物
    function generateFood() {
        const maxX = canvasWidth / gridSize - 1;
        const maxY = canvasHeight / gridSize - 1;
        const foodX = Math.floor(Math.random() * maxX) * gridSize;
        const foodY = Math.floor(Math.random() * maxY) * gridSize;
        
        // 确保食物不会生成在蛇身上
        for (let i = 0; i < snake.length; i++) {
            if (snake[i].x === foodX && snake[i].y === foodY) {
                return generateFood();
            }
        }
        
        return {
            x: foodX,
            y: foodY
        };
    }
    
    // 绘制游戏
    function draw() {
        // 清空画布
        ctx.fillStyle = '#333';
        ctx.fillRect(0, 0, canvasWidth, canvasHeight);
        
        // 绘制蛇
        for (let i = 0; i < snake.length; i++) {
            ctx.fillStyle = i === 0 ? '#4caf50' : '#8bc34a';
            ctx.fillRect(snake[i].x, snake[i].y, gridSize, gridSize);
            
            // 绘制蛇身边框
            ctx.strokeStyle = '#333';
            ctx.strokeRect(snake[i].x, snake[i].y, gridSize, gridSize);
        }
        
        // 绘制食物
        ctx.fillStyle = '#ff5722';
        ctx.fillRect(food.x, food.y, gridSize, gridSize);
        
        // 绘制分数
        ctx.fillStyle = 'white';
        ctx.font = '20px Arial';
        ctx.fillText(`得分: ${score}`, 10, 30);
    }
    
    // 移动蛇
    function moveSnake() {
        // 创建新的蛇头
        const head = {x: snake[0].x, y: snake[0].y};
        
        // 根据方向移动蛇头
        if (direction === 'right') head.x += gridSize;
        if (direction === 'left') head.x -= gridSize;
        if (direction === 'up') head.y -= gridSize;
        if (direction === 'down') head.y += gridSize;
        
        // 检查碰撞边界
        if (head.x >= canvasWidth) head.x = 0;
        if (head.x < 0) head.x = canvasWidth - gridSize;
        if (head.y >= canvasHeight) head.y = 0;
        if (head.y < 0) head.y = canvasHeight - gridSize;
        
        // 将新蛇头添加到蛇身前面
        snake.unshift(head);
        
        // 检查是否吃到食物
        if (head.x === food.x && head.y === food.y) {
            // 吃到食物，得分增加，生成新食物
            score += 10;
            food = generateFood();
            
            // 加速游戏
            if (score % 50 === 0 && gameSpeed > 50) {
                gameSpeed -= 10;
                clearInterval(gameLoop);
                gameLoop = setInterval(gameUpdate, gameSpeed);
            }
        } else {
            // 没有吃到食物，移除蛇尾
            snake.pop();
        }
        
        // 检查蛇头是否碰到蛇身
        for (let i = 1; i < snake.length; i++) {
            if (head.x === snake[i].x && head.y === snake[i].y) {
                // 游戏结束
                gameOver();
                return;
            }
        }
    }
    
    // 游戏更新
    function gameUpdate() {
        if (!isPaused) {
            moveSnake();
            draw();
        }
    }
    
    // 游戏结束
    function gameOver() {
        clearInterval(gameLoop);
        
        // 绘制游戏结束信息
        ctx.fillStyle = 'rgba(0, 0, 0, 0.7)';
        ctx.fillRect(0, 0, canvasWidth, canvasHeight);
        
        ctx.fillStyle = 'white';
        ctx.font = '30px Arial';
        ctx.fillText('游戏结束!', canvasWidth / 2 - 80, canvasHeight / 2 - 30);
        
        ctx.font = '20px Arial';
        ctx.fillText(`最终得分: ${score}`, canvasWidth / 2 - 70, canvasHeight / 2 + 10);
        ctx.fillText('按空格键重新开始', canvasWidth / 2 - 100, canvasHeight / 2 + 50);
    }
    
    // 键盘控制
    function handleKeyDown(e) {
        // 防止按键滚动页面
        if (e.key === 'ArrowUp' || e.key === 'ArrowDown' || e.key === 'ArrowLeft' || e.key === 'ArrowRight' || e.key === ' ') {
            e.preventDefault();
        }
        
        if (e.key === 'ArrowRight' && direction !== 'left') {
            direction = 'right';
        } else if (e.key === 'ArrowLeft' && direction !== 'right') {
            direction = 'left';
        } else if (e.key === 'ArrowUp' && direction !== 'down') {
            direction = 'up';
        } else if (e.key === 'ArrowDown' && direction !== 'up') {
            direction = 'down';
        } else if (e.key === ' ') {
            // 空格键重新开始或暂停/继续
            if (gameLoop === undefined) {
                // 重新开始游戏
                snake = [
                    {x: 5 * gridSize, y: 5 * gridSize},
                    {x: 4 * gridSize, y: 5 * gridSize},
                    {x: 3 * gridSize, y: 5 * gridSize}
                ];
                direction = 'right';
                food = generateFood();
                score = 0;
                gameSpeed = 120;
                gameLoop = setInterval(gameUpdate, gameSpeed);
            } else {
                // 暂停/继续
                isPaused = !isPaused;
                
                // 显示暂停状态
                if (isPaused) {
                    ctx.fillStyle = 'rgba(0, 0, 0, 0.5)';
                    ctx.fillRect(0, 0, canvasWidth, canvasHeight);
                    ctx.fillStyle = 'white';
                    ctx.font = '30px Arial';
                    ctx.fillText('已暂停', canvasWidth / 2 - 60, canvasHeight / 2);
                    ctx.font = '20px Arial';
                    ctx.fillText('按空格键继续', canvasWidth / 2 - 90, canvasHeight / 2 + 40);
                }
            }
        }
    }
    
    // 注册键盘事件
    document.addEventListener('keydown', handleKeyDown);
    
    // 启动游戏循环
    gameLoop = setInterval(gameUpdate, gameSpeed);
    
    // 绘制初始状态
    draw();
    
    // 返回清理函数
    return function cleanup() {
        clearInterval(gameLoop);
        document.removeEventListener('keydown', handleKeyDown);
    };
}